<!DOCTYPE html>
<html>
<head>
    <title>TODOList</title>
</head>
<body>
    <h1>TODOList</h1>
    <form id="taskForm">
        <input type="text" name="text" placeholder="New Task" required />
        <button type="submit">Add</button>
        <button type="button" id="deleteAll">Delete All</button>
    </form>
    <ul id="taskList"></ul>
    
    <script>
        const userId = new URLSearchParams(window.location.search).get('userId');

        document.getElementById('taskForm').onsubmit = async (e) => {
            e.preventDefault();
            const formData = new FormData(e.target);
            const data = Object.fromEntries(formData);
            data.user_id = userId;
            await fetch('/tasks', { method: 'POST', body: JSON.stringify(data), headers: { 'Content-Type': 'application/json' } });
            loadTasks();
        };

        document.getElementById('deleteAll').onclick = async () => {
            try {
                const response = await fetch(`/tasks/${userId}`, { method: 'DELETE' });
                if (response.ok) {
                    loadTasks();
                } else {
                    const errorData = await response.json();
                    alert(`Failed to delete all tasks: ${errorData.message}`);
                }
            } catch (error) {
                alert(`Error occurred: ${error.message}`);
            }
        };

        const loadTasks = async () => {
            try {
                const response = await fetch(`/tasks/${userId}`);
                if (response.ok) {
                const { tasks } = await response.json();
                console.log("Loaded tasks:", tasks); // 确保这里能打印出新的任务列表
                const taskList = document.getElementById('taskList');
                taskList.innerHTML = ''; // 清空任务列表
                tasks.forEach(task => {
                    const li = document.createElement('li');
                    li.textContent = task.text;

                    // Create an input to update the task name
                    const editInput = document.createElement('input');
                    editInput.placeholder = 'Edit Task';
                    editInput.value = task.text;

                    // Update task
                    const updateButton = document.createElement('button');
                    updateButton.textContent = 'Update';
                    updateButton.onclick = async () => {
                    const updatedText = editInput.value;
                    await fetch(`/tasks/${task.id}`, {
                        method: 'PUT',
                        body: JSON.stringify({ text: updatedText }),
                        headers: { 'Content-Type': 'application/json' }
                    });
                    loadTasks();
                    };

                    // Delete single task
                    const deleteButton = document.createElement('button');
                    deleteButton.textContent = 'Delete';
                    deleteButton.onclick = async () => {
                    try { 
                        const response = await fetch(`/tasks/${task.id}`, { method: 'DELETE' });
                        if (!response.ok) {
                        const errorData = await response.json();
                        alert(`Failed to delete task: ${errorData.error || 'Unknown Error'}`);
                        return;
                        }

                        console.log(`Successfully deleted task with ID: ${task.id}`);
                        await loadTasks(); // 刷新任务列表
                    } catch (error) {
                        alert(`Error occurred: ${error.message}`);
                        console.error(`Error details: ${error}`);
                    }
                    };

                    // Append elements
                    li.appendChild(editInput);
                    li.appendChild(updateButton);
                    li.appendChild(deleteButton);
                    taskList.appendChild(li);
                });
                } else {
                console.error("Failed to load tasks. Status:", response.status);
                alert('Failed to load tasks.');
                }
            } catch (error) {
                console.error("Error loading tasks:", error);
                alert('Error occurred while loading tasks.');
            }
            };

        loadTasks(); 
    </script>
</body>
</html>